<?php

namespace app\backend\controller\member;

use app\common\controller\Backend;
use app\common\model\MemberAccount as MemberAccountModel;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Provider\Wechat;

/**
 * @ControllerAnnotation (title="会员余额")
 * Class MemberLevel
 * @package app\backend\controller\member
 */
class MemberAccount extends Backend
{

    protected Wechat $payment;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->modelClass = new MemberAccountModel();
//        $this->payment = Pay::wechat(config('payment.wechat.default'));
    }

    public function index()
    {
        if (request()->isAjax()) {
            if (request()->param('selectFields')) {
                $this->selectList();
            }
            list($this->page, $this->pageSize, $sort, $where) = $this->buildParames();
            $list = $this->modelClass
                ->where($where)
                ->with('member')
                ->order('create_time', 'desc')
                ->paginate([
                    'list_rows' => $this->pageSize,
                    'page' => $this->page,
                ]);
            $result = ['code' => 0, 'msg' => lang('Get Data Success'), 'data' => $list->items(), 'count' => $list->total()];
            return json($result);
        }
        return view();
    }

    public function edit()
    {
        $id = request()->param($this->modelClass->getPk());
        $list = $this->modelClass
            ->with(['member', 'third'])
            ->find($id);
        if (empty($list)) $this->error(lang('Data is not exist'));
        if (request()->isPost()) {

            $post = request()->post();
            $rule = [];
            try {
                $this->validate($post, $rule);
            } catch (ValidateException $e) {
                $this->error(lang($e->getMessage()));
            }
            foreach ($post as $k => $v) {
                if (is_array($v)) {
                    $post[$k] = implode(',', $v);
                }
            }
            Db::startTrans();
            try {
                if ($post['status'] == 2) {
                    $trade_no = get_ordersn('TR');
                    $post['out_detail_no'] = $trade_no;
                    if (empty($list['third']['openid'])) {
                        throw new \Exception("微信未绑定");
                    }
                    $transfer_detail_list = [
                        [
                            'out_detail_no' => $trade_no,
                            'transfer_amount' => $list['money_change'] * 100,
                            'transfer_remark' => date('Ymd H:i:s'),
                            'openid' => $list['third']['openid'],
//                            'user_name' => $list['member']['realname']
                        ]
                    ];
                    $bach_no = get_ordersn('BN', true);
                    $post['out_batch_no'] = $bach_no;
                    $data = [
                        'out_batch_no' => $bach_no,
                        'batch_name' => date('Ymd H:i:s'),
                        'batch_remark' => date('Ymd H:i:s'),
                        'total_amount' => $list['money_change'] * 100,
                        'total_num' => 1,
                        'transfer_detail_list' => $transfer_detail_list
                    ];
                    Pay::config(config('payment'));
                    $result = Pay::wechat()->transfer($data);
                    if ($result['code'] !== 'SUCCESS') {
                        throw new \Exception('【微信】' . $result['message']);
                    }

                }
                $save = $list->save($post);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error(lang($e->getMessage()));
            }
            $save ? $this->success(lang('operation success')) : $this->error(lang('operation failed'));
        }
        $view = ['formData' => $list->toArray(), 'title' => lang('Add'),];
        return view('add', $view);
    }

    /**
     * @NodeAnnotation (title="添加")
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'name|等级名称' => [
                    'require' => 'require',
                    'max' => '255',
                    'unique' => 'member_level',
                ],
                'description|描述' => [
                    'max' => '255',
                ],
            ];
            $this->validate($post, $rule);
            try {
                $save = $this->modelClass->save($post);
            } catch (\Exception $e) {
                $this->error(lang('Save failed'));
            }
            $save ? $this->success(lang('Save success')) : $this->error(lang('Save failed'));
        }
        $view = [
            'formData' => '',
            'title' => lang('Add'),
        ];
        return view('', $view);
    }

}